package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Suave
 * @date 2024/8/11
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    private static final String WX_LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";

    /**
     * 微信登录
     * @param userLoginDTO
     * @return
     */
    public User wxLogin(UserLoginDTO userLoginDTO) {
        String openId = getOpenId(userLoginDTO.getCode());
//        判断openId是否为空
        if(openId == null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
//        判断当前用户是否为新用户
        User user = userMapper.selectByOpenId(openId);
//        如果是新用户
        if(user == null){
            user = User.builder()
                    .openid(openId)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.save(user);
        }


        return user;
    }

    /**
     * 调用微信服务接口获取openid
     * @param code
     * @return
     */
    public String getOpenId(String code){
//        调用微信服务接口获取openid
        Map<String,String> map = new HashMap<>();
        map.put("appid","wx490487c720102880");
        map.put("secret","f6dc06884d2e5e07bc4e5e32968edcee");
        map.put("js_code",code);
        map.put("grant_type","authorization_code");
//        发送请求
        String json = HttpClientUtil.doGet(WX_LOGIN_URL, map);
//        把json字符串解析成json对象
        JSONObject jsonObject = JSONObject.parseObject(json);
        String openid = jsonObject.getString("openid");
        return openid;
    }
}
